import helper from '@/helper/helper'
import store from '../index'
import router, { resetRouter } from '@/router'
import config from '@/helper/config'
import { authLogin, userLogout, getAuthToken, getInfo } from '@/api'
import { Modal } from 'ant-design-vue'
// import { getAuthToken, userLogout } from '@/api'
const User = {
  namespaced: false,
  state: {
    userInfo: {},
    roles: [],
    refreshToken: ''
  },
  getters: {
    userInfo (state) {
      return state.userInfo
    },
    roles (state) {
      return state.roles
    },
    refreshToken (state) {
      return state.refreshToken
    }
  },
  mutations: {
    SET_USER_INFO (state, value) {
      state.userInfo = value
    },
    SET_ROLES (state, value) {
      state.roles = value
    },
    SET_REFRESH_TOKEN (state, value) {
      state.refreshToken = value
    }
  },
  actions: {
    async login ({ commit }, params) {
      // 调用接口
      const { data } = await authLogin(params)
      // 接口返回结构
      // {
      //   "msg":"操作成功",
      //   "code":200,
      //   "data":{
      //     "access_token":"eyJhbGciOiJIUzUxMiJ9.eyJxxxx",
      //     "expires_in":720,
      //     "username":"若依"
      //   }
      // }
      helper.setToken(data.access_token)
      helper.pageHide()
      return true
    },
    // 授权码获取token
    async getTokenByCode ({ commit }, params) {
      const { data } = await getAuthToken(params)
      // 接口返回结构
      // {
      //   "msg":"操作成功",
      //   "code":200,
      //   "data":{
      //     "access_token":"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.xxxxxx",
      //     "token_type":"bearer",
      //     "refresh_token":"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.xxxxxx",
      //     "expires_in":3599,
      //     "scope":"all",
      //     "user_id":1,
      //     "user_name":"admin",
      //     "nick_name":"admin",
      //     "global_token":"5b433c5e-6c4b-4a8c-9cb7-a73f2a7ddfd9",
      //     "dept_id":100,
      //     "jti":"d2c82d32-a84f-4dd1-b00f-078ca3b3f914"
      //   }
      // }
      helper.setToken(data.access_token)
      commit('SET_REFRESH_TOKEN', data.refresh_token)
      helper.pageHide()
      return data
    },
    // 业务系统----获取用户详细信息
    async getUserInfo ({ commit }) {
      const { user, permissions, roles } = await getInfo(config.clientId)
      // 接口返回结构
      // {
      //   "msg":"操作成功",
      //   "code":200,
      //   "permissions":["*:*:*"],
      //   "roles":["admin"],
      //   "user":{
      //     "searchValue":null,
      //     "createBy":"admin",
      //     "createTime":"2022-03-03 11:28:13",
      //     "updateBy":null,
      //     "updateTime":null,
      //     "remark":"管理员",
      //     "params":{},
      //     "userId":1,
      //     "deptId":100,
      //     "userName":"admin",
      //     "nickName":"若依",
      //     "email":"ry@163.com",
      //     "phonenumber":"15888888888",
      //     "sex":"1",
      //     "avatar":"http://minio-tasjnn.public-minio.10.10.7.51.nip.io:30476/develop/2022/09/20/f2c82fb7-80fa-4b67-8629-b792b683f3fe.jpeg",
      //     "password":"$2a$10$VAb/4mHFcd75y.MQiGyvk.2aNqWIFzCTXdvHYpjxBn5Au8o2jGpJG",
      //     "status":"0",
      //     "delFlag":"0",
      //     "loginIp":"127.0.0.1",
      //     "loginDate":"2022-03-03T11:28:13.000+08:00",
      //     "dept":{
      //       "searchValue":null,
      //       "createBy":null,
      //       "createTime":null,
      //       "updateBy":null,
      //       "updateTime":null,
      //       "remark":null,
      //       "params":{},
      //       "deptId":100,
      //       "parentId":0,
      //       "ancestors":"0",
      //       "ancestorsName":null,
      //       "deptName":"中国恩菲工程技术有限公司",
      //       "orderNum":"0",
      //       "leader":"admin",
      //       "phone":null,
      //       "email":null,
      //       "status":"0",
      //       "delFlag":null,
      //       "parentName":null,
      //       "children":[]
      //     },
      //     "roles":[
      //       {
      //         "searchValue":null,
      //         "createBy":null,
      //         "createTime":null,
      //         "updateBy":null,
      //         "updateTime":null,
      //         "remark":null,
      //         "params":{},
      //         "roleId":1,
      //         "roleName":"超级管理员",
      //         "roleKey":"admin",
      //         "roleSort":"1",
      //         "dataScope":"1",
      //         "menuCheckStrictly":false,
      //         "deptCheckStrictly":false,
      //         "status":"0",
      //         "delFlag":null,
      //         "flag":false,
      //         "menuIds":null,
      //         "deptIds":null,
      //         "admin":true
      //       }
      //     ],
      //     "posts":[{"searchValue":null,"createBy":null,"createTime":null,"updateBy":null,"updateTime":null,"remark":null,"params":{},"postId":1,"postCode":"ceo","postName":"董事长","postSort":"1","status":"0","flag":false}],
      //     "roleIds":null,"postIds":null,"major":null,"roleId":null,"admin":true
      //   }
      // }
      commit('SET_USER_INFO', user)
      commit('SET_ROLES', roles)
      store.commit('SET_PERMISSION', permissions)
      helper.pageHide()
    },
    logout ({ dispatch }) {
      Modal.confirm({
        title: '提示',
        content: '确定退出登录吗?',
        async onOk () {
          try {
            const { code } = await userLogout()
            if (code === 200) {
              helper.msg.success('退出成功!')
            }
          } finally {
            dispatch('clearStore')
            // 统一认证逻辑直接放到子系统------
            // router.push({ name: 'login' })
            dispatch('tagsView/delAllViews')
            if (config.systemType === 'business') {
              const redirectUri = encodeURIComponent('http://' + window.location.host + '/')
              window.location.href = `${config.ssoUrl}/login?client_id=${config.clientId}&redirect_uri=${redirectUri}`
            } else {
              router.push({ name: 'login' })
            }
            Modal.destroyAll()
          }
        },
        onCancel () {
          helper.msg.success('取消退出!')
        }
      })
    },
    clearStore ({ commit }) {
      commit('SET_USER_INFO', {})
      commit('SET_ROLES', [])
      store.commit('SET_PERMISSION', [])
      store.commit('SET_RouteNames', [])
      resetRouter()
      helper.removeToken()
      helper.storage.clear()
    }
  }
}

export default User
